<template>
  <view class="page">
    <view class="address">
      <view v-if="!address" class="emptyAddr" @click="getAddress">
        选择地址
      </view>
      <view v-else class="info">
        {{address}}
        <view class="user">
          {{userName}} {{phone}}
        </view>
      </view>
      
    </view>
    <view class="goodsList">
      <view class="title">已选商品</view>
      <view class="item"
        v-for="item in goodsChecked"
        :key="item.goods_id"
      >
        <u-image width="191" height="191" :src="item.goods_pic" mode=""></u-image>
        <view class="info">
          <view class="title u-line-2">{{item.goods_name}}</view>
          <view class="priceBar">
            <view class="price">¥ {{item.goods_price}}</view>
            <view class="number">x {{item.number}}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="status">
      <view class="priceWrap">
        合计: <text class="price">¥ 39999</text>
      </view>
      <view @click="toPay" class="btn" :class="{active: address}">去支付</view>
    </view>
  </view>
</template>

<script>
import {mapGetters, mapMutations, mapState, mapActions} from 'vuex'
export default {
  data() {
    return {
      address: '',
      userName: '',
      phone: ''
    }
  },
  computed: {
    ...mapState('user', ['token']),
    ...mapGetters(['goodsChecked', 'totalPrice'])
  },
  methods: {
    ...mapActions('user', ['wxLogin']),
    ...mapMutations('cart', ['clearCart']),
    async getAddress() {
      const [err, res] = await uni.chooseAddress();
      if (!err) {
        console.log(res);
        const {provinceName,cityName,countyName,detailInfo,postalCode,userName, telNumber} = res
        this.address = `${provinceName} ${cityName} ${countyName} ${detailInfo} ${postalCode}`
        this.userName = userName
        this.phone = telNumber
      }
    },
    async toPay() {
      // 校验地址
      if (!this.address) {
        uni.showToast({title: '请先选择地址', icon: 'none'})
        return
      }
      // 登录
      // this.$store.dispatch('user/wxLogin')
      if (!this.token) {
        await this.wxLogin()
      }

      // 添加订单
      const order_number = await this.createOrder()
      
      // 添加预付单
      const paymentInfo = await this.createPayment(order_number)

      // 调起支付
      const [err, res] = await uni.requestPayment(paymentInfo)
      console.log('支付错误', err);
      console.log('支付结果', res);
      if (!err) {
        this.clearCart()
        uni.switchTab({
          url: '/pages/index/index'
        })
      }
    },
    // async wxLogin() {
    //   // 拿到用户信息
    //   const [errProfile, resProfile] = await uni.getUserProfile({desc: '为您提供更好的服务'})
    //   console.log(resProfile);
    //   // 拿到微信临时验证code
    //   const [errCode, resCode] = await uni.login()
    //   console.log(resCode);
    //   // 换取 token
    //   const {message} = await this.$u.post('/users/wxlogin', {
    //     encryptedData: resProfile.encryptedData,
    //     iv: resProfile.iv,
    //     rawData: resProfile.rawData,
    //     signature: resProfile.signature,
    //     code: resCode.code
    //   })
    //   console.log(message.token);
    //   return message.token
    // },
    async createOrder() {
      const goods_data = {
        order_price: this.totalPrice,
        consignee_addr: `${this.address} ${this.userName} ${this.phone}`,
        goods: this.goodsChecked.map(item=>{
          return {
            goods_id: item.goods_id,
            goods_number: item.number,
            goods_price: item.goods_price
          }
        })
      }
      const {message} = await this.$u.post('/my/orders/create', goods_data)
      console.log(message);
      return message.order_number
    },
    async createPayment(order_number) {
      const {message} = await this.$u.post('/my/orders/req_unifiedorder', {order_number})
      console.log(message);
      return message.pay
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  padding: 20rpx 0;
  min-height: 100vh;
  background: #f9f9f9;
}
.address {
  margin: 0 20rpx;
  background: #fff;
  display: flex;
  justify-content: center;
  min-height: 187rpx;
  align-items: center;
  .emptyAddr {
    margin: 50rpx;
    line-height: 80rpx;
    border: 4rpx solid $theme-color;
    padding: 0 60rpx;
    border-radius: 45rpx;
    color: $theme-color;
    font-weight: bold;
    font-size: 30rpx;
  }
  .info {
    padding: 16rpx 0;
    color: #434343;
    font-size: 30rpx;
    .user {
      margin-top: 20rpx;
    }
  }
}
.goodsList {
  background: #fff;
  margin: 35rpx 20rpx;
  padding: 17rpx 26rpx;
  .title {
    color: #434343;
    font-size: 26rpx;
  }
  .item {
    display: flex;
    margin: 20rpx 0;
    .info {
      flex: 1;
      padding: 20rpx 0;
      padding-left: 20rpx;
      height: 191rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .priceBar {
        display: flex;
        justify-content: space-between;
        .price {
          color: $theme-color;
        }
      }
    }
  }
}
.status {
  position: fixed;
  bottom: 0;
  left: 0;
  background: #fff;
  width: 100%;
  display: flex;
  height: 83rpx;
  align-items: center;
  padding: 0 20rpx;
  .priceWrap {
    flex: 1;
    .price {
      color: $theme-color;
      padding-left: 20rpx;
    }
  }
  .btn {
    line-height: 52rpx;
    background: #999;
    color: #fff;
    padding: 0 26rpx;
    border-radius: 26rpx;
    &.active {
      background: $theme-color;
    }
  }
}
</style>